﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Home.Utils;
using NhanAi.DAO;
using NhanAi.DAO.Mix;
using NhanAi.Entity;
using NhanAi.App_Code;
using System.Web.Configuration;
namespace NhanAi.Admin
{
    public partial class CreatePost : BasePage
    {
        string imageUrl;
        List<Taxonomy> taxonomies;
       // List<Taxonomy> cTaxonomies;
        public string ImageUrl { get { return imageUrl; } }
        public List<Taxonomy> Taxonomies { get { return taxonomies; } }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Authenticate();
            TaxonomyDao daoTax = new TaxonomyDao();
            pstAttribute.PostAtt = 1;
            cmbStatus.Items.Add(new ListItem("Nháp", NAConstants.POST_STA_DRAFT.ToString()));
            cmbStatus.Items.Add(new ListItem("Cho phép đăng", NAConstants.POST_STA_POST.ToString()));

            taxonomies = daoTax.ReadAll();
            
            rptTaxonomies.DataSource = taxonomies;
            rptTaxonomies.DataBind();
            SetCurrentPage("Post");
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            PostModel dao = new PostModel();
            Post p = new Post();
            bool rs = false;
            try
            {                
                p.Title = txtTitle.Text;
                p.TitleEn = txtTitleEn.Text;
                p.Content = PostContent.Value;
                p.ContentEn = PostContentEn.Value;
                p.Status = int.Parse(cmbStatus.SelectedItem.Value);
                p.PostAttribute = TypeWrapper.GetInt32(Request["ThuocTinh"]);
                p.PostDate = DateTime.Now;
                p.ModifiedDate = DateTime.Now;
                p.MenuOrder = 0;
                p.Protected = chkProtected.Checked;
                p.Guid = Request["txtImage"] == null ? "" : Request["txtImage"];
                imageUrl = p.Guid;
                p.PostType = "post";
                p.Excerpt = StringUltility.GetExcerpt(p.Content,NAConstants.EXCERPT_LEN);
                p.ExcerptEn = StringUltility.GetExcerpt(p.ContentEn,NAConstants.EXCERPT_LEN);
                p.Name = "";

               // if (p.Excerpt.Length > NAConstants.EXCERPT_LEN) p.Excerpt.Substring(0, NAConstants.EXCERPT_LEN);
                //if (p.ExcerptEn.Length > NAConstants.EXCERPT_LEN) p.ExcerptEn.Substring(0, NAConstants.EXCERPT_LEN);
                if (Session["user"] != null)
                {
                    User u = (User)Session["user"];
                    p.AuthorId = u.Id;
                }
                string taxIds = Request["taxonomy"];
                if (!String.IsNullOrEmpty(taxIds))
                {
                    List<Taxonomy> selectedTaxs=new List<Taxonomy>();
                    string[] data = taxIds.Split(',');
                    foreach (string d in data)
                    {
                        Taxonomy t = new Taxonomy(TypeWrapper.GetInt32(d));
                        selectedTaxs.Add(t);
                    }
                    p.Taxonomies=selectedTaxs;
                }
                dao.Create(p);
                SetMessage("Thêm mới thành công", "");
                if (p.Status == NhanAi.App_Code.NAConstants.POST_STA_POST && chkSendMail.Checked)
                {
                    SendNotificationEmail(p);
                }
            }
            catch (Exception ex)
            {
                SetMessage("Đã xảy ra lỗi","");
            }
            
            if(rs)Redirect("/Admin/EditPost.aspx?id=" + p.Id);
        }

        public void SendNotificationEmail(Post p)
        {            
            UserDao dao = new UserDao();
            List<string> emails = dao.GetFollowedEmails(15);
            if (emails.Count > 0)
            {
                try
                {
                    string uid = WebConfigurationManager.AppSettings["email_uid"];
                    string pwd = WebConfigurationManager.AppSettings["email_password"];
                    string server = WebConfigurationManager.AppSettings["email_server"];
                    string port = WebConfigurationManager.AppSettings["email_port"];
                    string name = WebConfigurationManager.AppSettings["email_name"];
                    string postUrl = WebConfigurationManager.AppSettings["post_url"];
                    KTEmail mailer = new KTEmail(server, Home.Utils.TypeWrapper.GetInt32(port), uid, pwd, name);
                    foreach (string em in emails)
                    {
                        mailer.Reciepients.Add(em);
                        string title = "Nhan Ai clinic - Bai viet moi (New post)";
                        string body = "Một bài viết mới được đăng tại website của NhanAiClinic, vui lòng nhấp vào liên kết bên dưới để xem."
                            + "</br>"
                            + "<a href='" + postUrl + "?id=" + p.Id + "'>" + (p.Title != "" ? p.Title : "Nhấp vào đây") + "</a></br>"
                            + "(There is a new post on NhanAiClinic's website), please click followed link to view the post)</br>"
                            + "<a href='" + postUrl + "?id=" + p.Id + "'>" + (p.TitleEn != "" ? p.TitleEn : "Click here") + "</a></br>";
                        mailer.SendMailAsync(title, body);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
        }
    }
}